


const Cu = Components.utils;
function require(url) {
    let scope = {};
    Cu.import(url, scope);
    return scope;
}
let {MiscUtils} = require("chrome://jsm/content/utils.js");
let {Prefs} = require("chrome://jsm/content/Preferences.js");
let {Dialogs} = require("chrome://jsm/content/Dialogs.js");
let {OS} = require("resource://gre/modules/osfile.jsm");


window.onload = function () {
    let default_path = Prefs.defaultMacroPath;
    var folder = document.getElementById("imacros-folder-name");
    var filename = document.getElementById('imacros-file-name');
    if("arguments" in window && window.arguments.length > 0) {
        filename.value = window.arguments[0].filename;
        folder.value = window.arguments[0].folder ? 
            window.arguments[0].folder : default_path;
    } else {
        filename.value = "untitled";
        folder.value = default_path;
    }
};


function chooseFolder() {
    let folder = document.getElementById("imacros-folder-name");
    let defdir = null;
    try {
        defdir = OS.Path.normalize(folder.value);
    } catch (e) {
        
        defdir = Prefs.defaultMacroPath;
    }
    Dialogs.browseForFolder("", defdir).then(dir => {
        if (dir) {
            folder.value = dir;
        }
    });
}


function onAccept () {
    if("arguments" in window && window.arguments.length > 0) {
        let folder = document.getElementById("imacros-folder-name");
        let path = null;
        try {
            path = OS.Path.normalize(folder.value);
        } catch(e) {
            window.alert("Wrong path: "+folder.value);
            return;
        }
        let filename = document.getElementById('imacros-file-name');
        if (!filename.value) {
            window.alert("File name can not be empty!");
            return;
        }
        let bookmark = document.getElementById('bookmark');

        window.arguments[0].folder = path;
        window.arguments[0].filename = filename.value;
        window.arguments[0].confirm = true;
        window.arguments[0].bookmark = bookmark.checked;
    }
    window.close();
}


function onCancel () {
    if("arguments" in window && window.arguments.length > 0) {
        window.arguments[0].confirm = false;
    }
    window.close();
}
